/*******************************************************************************
 * $Header$
 * $Revision$
 * $Date$
 *
 *==============================================================================
 *
 * Copyright©hxlife/hulife 
 * All rights reserved.
 * 
 * Created on 2017年11月10日
 *******************************************************************************/

package com.hualife.md.member.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;

import com.hualife.md.constants.MDConstants;
import com.hualife.md.member.dao.ex.mapper.AdOrganizationalunitQueryMapper;
import com.hualife.md.member.dao.ex.mapper.LabranchgroupQueryMapper;
import com.hualife.md.member.dao.ex.mapper.LdcomQueryMapper;
import com.hualife.md.member.dao.mybatis.entity.MemberInfoExample;
import com.hualife.md.member.dao.mybatis.entity.OrganizationInfo;
import com.hualife.md.member.dao.mybatis.entity.OrganizationalunitInfo;
import com.hualife.md.member.dao.mybatis.entity.SynAdOrganizationalunit;
import com.hualife.md.member.dao.mybatis.entity.SynAdOrganizationalunitExample;
import com.hualife.md.member.dao.mybatis.entity.SynLisLaagentExample;
import com.hualife.md.member.dao.mybatis.entity.SynLisLabranchgroup;
import com.hualife.md.member.dao.mybatis.entity.SynLisLabranchgroupExample;
import com.hualife.md.member.dao.mybatis.entity.SynLisLdcom;
import com.hualife.md.member.dao.mybatis.mapper.MemberInfoMapper;
import com.hualife.md.member.dao.mybatis.mapper.OrganizationInfoMapper;
import com.hualife.md.member.dao.mybatis.mapper.OrganizationalunitInfoMapper;
import com.hualife.md.member.dao.mybatis.mapper.SynAdOrganizationalunitMapper;
import com.hualife.md.member.dao.mybatis.mapper.SynLisLaagentMapper;
import com.hualife.md.member.dao.mybatis.mapper.SynLisLabranchgroupMapper;
import com.hualife.md.member.dao.mybatis.mapper.SynLisLdcomMapper;
import com.hualife.md.member.service.IOrganizationIntegrateService;
import com.hualife.support.exception.BusinessException;

/**
 * @description: TODO 此处填写 class 信息
 * @author 孙小冬 (mailto:sunxiaodong001@hualife.cc)
 */
@Service("organizationIntegrateService")
public class OrganizationIntegrateServiceImpl implements
		IOrganizationIntegrateService {

	private static final Logger logger = LoggerFactory
			.getLogger(OrganizationIntegrateServiceImpl.class);

	@Autowired
	private OrganizationInfoMapper organizationInfoMapper;
	@Autowired
	private LdcomQueryMapper ldcomQueryMapper;
	@Autowired
	private LabranchgroupQueryMapper labranchgroupQueryMapper;
	@Autowired
	private SynLisLdcomMapper synLisLdcomMapper;
	@Autowired
	private SynLisLabranchgroupMapper synLislabranchgroupMapper;
	@Autowired
	private MemberInfoMapper memberInfoMapper;
	@Autowired
	private SynLisLaagentMapper synLisLaagentMapper;
	@Autowired
	private OrganizationalunitInfoMapper organizationalunitInfoMapper;
	@Autowired
	private SynAdOrganizationalunitMapper synAdOrganizationalunitMapper;
	@Autowired
	private AdOrganizationalunitQueryMapper adOrganizationalunitQueryMapper;

	@Autowired
	private TaskExecutor taskExecutor;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.hualife.md.member.service.IMemberIntegrateService#integrate()
	 */
	@Override
	public void integrate() {

		while (true) {
			CopyOnWriteArrayList<SynLisLdcom> ldcomList = ldcomQueryMapper
					.selectUnIntegratedLdcom();
			if (ldcomList.size() == 0)
				break;
			for (SynLisLdcom ldcom : ldcomList) {
				try {
					taskExecutor.execute(new Runnable() {
						public void run() {
							saveOrganizationInfo(ldcom);
							ldcomList.remove(ldcom);
						}
					});
				} catch (Throwable e) {
					e.printStackTrace();
					ldcomList.remove(ldcom);
				}
			}

			while (true) {

				if (ldcomList.size() == 0) {
					//  任务都执行完毕，跳出循环
					break;
				}

				try {
					Thread.sleep(1000);
				} catch (Throwable e) {
					break;
				}
			}
		}

		while (true) {

			CopyOnWriteArrayList<SynLisLabranchgroup> labranchgroupList = labranchgroupQueryMapper
					.selectUnIntegratedLabranchgroup();
			if (labranchgroupList.size() == 0)
				break;
			for (SynLisLabranchgroup labranchgroup : labranchgroupList) {
				try {
					taskExecutor.execute(new Runnable() {
						public void run() {
							saveOrganizationInfo(labranchgroup);
							labranchgroupList.remove(labranchgroup);
						}
					});
				} catch (Throwable e) {
					e.printStackTrace();
					labranchgroupList.remove(labranchgroup);
				}
			}

			while (true) {
				if (labranchgroupList.size() == 0) {
					//  任务都执行完毕，跳出循环
					break;
				}

				try {
					Thread.sleep(1000);
				} catch (Throwable e) {
					break;
				}
			}
		}

	}

	private void saveOrganizationInfo(SynLisLdcom ldcom) {
		StringBuffer affiliationCode = new StringBuffer();
		StringBuffer affiliationName = new StringBuffer();
		StringBuffer wholeOrganizationCode = new StringBuffer();
		StringBuffer wholeOrganizationName = new StringBuffer();
		OrganizationInfo organizationInfo = new OrganizationInfo();
		try {
			if (ldcom.getComcode() == null
					|| "".equals(ldcom.getComcode().trim())) {
				return;
			}
			String comcode = ldcom.getComcode().trim();
			organizationInfo.setOrganizationCode(comcode);
			organizationInfo.setOrganizationName(ldcom.getName());
			organizationInfo.setOrganizationShortname(ldcom.getShortname());
			if (!comcode.startsWith(MDConstants.TOP_ORGANIZATION)) {
				throw new BusinessException("管理机构编码异常！");
			}
			if (comcode.length() == 8) {
				affiliationCode.append(MDConstants.TOP_ORGANIZATION)
						.append(MDConstants.SEPARATOR_DOT)
						.append(comcode.substring(0, 4))
						.append(MDConstants.SEPARATOR_DOT)
						.append(comcode.substring(0, 6));
				affiliationName
						.append(MDConstants.TOP_ORGANIZATION_NAME)
						.append(MDConstants.SEPARATOR_SLANT)
						.append(synLisLdcomMapper.selectByPrimaryKey(
								comcode.substring(0, 4)).getShortname())
						.append(MDConstants.SEPARATOR_SLANT)
						.append(synLisLdcomMapper.selectByPrimaryKey(
								comcode.substring(0, 6)).getShortname());
				wholeOrganizationCode.append(MDConstants.TOP_ORGANIZATION)
						.append(MDConstants.SEPARATOR_DOT)
						.append(comcode.substring(0, 4))
						.append(MDConstants.SEPARATOR_DOT)
						.append(comcode.substring(0, 6))
						.append(MDConstants.SEPARATOR_DOT).append(comcode);
				wholeOrganizationName
						.append(MDConstants.TOP_ORGANIZATION_NAME)
						.append(MDConstants.SEPARATOR_SLANT)
						.append(synLisLdcomMapper.selectByPrimaryKey(
								comcode.substring(0, 4)).getShortname())
						.append(MDConstants.SEPARATOR_SLANT)
						.append(synLisLdcomMapper.selectByPrimaryKey(
								comcode.substring(0, 6)).getShortname())
						.append(MDConstants.SEPARATOR_SLANT)
						.append(synLisLdcomMapper.selectByPrimaryKey(comcode)
								.getShortname());
			} else if (comcode.length() == 6) {
				affiliationCode.append(MDConstants.TOP_ORGANIZATION)
						.append(MDConstants.SEPARATOR_DOT)
						.append(comcode.substring(0, 4));
				affiliationName
						.append(MDConstants.TOP_ORGANIZATION_NAME)
						.append(MDConstants.SEPARATOR_SLANT)
						.append(synLisLdcomMapper.selectByPrimaryKey(
								comcode.substring(0, 4)).getShortname());
				wholeOrganizationCode.append(MDConstants.TOP_ORGANIZATION)
						.append(MDConstants.SEPARATOR_DOT)
						.append(comcode.substring(0, 4))
						.append(MDConstants.SEPARATOR_DOT).append(comcode);
				wholeOrganizationName
						.append(MDConstants.TOP_ORGANIZATION_NAME)
						.append(MDConstants.SEPARATOR_SLANT)
						.append(synLisLdcomMapper.selectByPrimaryKey(
								comcode.substring(0, 4)).getShortname())
						.append(MDConstants.SEPARATOR_SLANT)
						.append(synLisLdcomMapper.selectByPrimaryKey(comcode)
								.getShortname());
			} else if (comcode.length() == 4) {
				affiliationCode.append(MDConstants.TOP_ORGANIZATION);
				affiliationName.append(MDConstants.TOP_ORGANIZATION_NAME);
				wholeOrganizationCode.append(MDConstants.TOP_ORGANIZATION)
						.append(MDConstants.SEPARATOR_DOT).append(comcode);
				wholeOrganizationName
						.append(MDConstants.TOP_ORGANIZATION_NAME)
						.append(MDConstants.SEPARATOR_SLANT)
						.append(synLisLdcomMapper.selectByPrimaryKey(comcode)
								.getShortname());
			} else if (comcode.length() == 2) {
				affiliationCode.append("-");
				affiliationName.append(MDConstants.TOP_ORGANIZATION_NAME);
				wholeOrganizationCode.append(comcode);
				wholeOrganizationName
						.append(MDConstants.TOP_ORGANIZATION_NAME)
						.append(MDConstants.SEPARATOR_SLANT)
						.append(synLisLdcomMapper.selectByPrimaryKey(comcode)
								.getShortname());
			} else {
				throw new BusinessException("管理机构编码异常！");
			}
			// 管理机构层级下用户总数的判断，直接通过like的方式
			int totalNumber = 0;
			// 内勤
			MemberInfoExample example1 = new MemberInfoExample();
			MemberInfoExample.Criteria criteria1 = example1.createCriteria();
			criteria1.andOrganizationCodeLike(comcode + "%");
			criteria1.andStateEqualTo("0");
			totalNumber += memberInfoMapper.countByExample(example1);

			organizationInfo.setAffiliationCode(affiliationCode.toString());
			organizationInfo.setAffiliationName(affiliationName.toString());
			organizationInfo.setWholeOrganizationCode(wholeOrganizationCode
					.toString());
			organizationInfo.setWholeOrganizationName(wholeOrganizationName
					.toString());
			organizationInfo.setTotalNumber(totalNumber);
			organizationInfo.setCategory("0");
			organizationInfo.setChannel("0");
			organizationInfo.setCreateTime(new Date());
			organizationInfo.setUpdateTime(new Date());
			organizationInfoMapper.deleteByPrimaryKey(organizationInfo
					.getOrganizationCode());
			organizationInfoMapper.insertSelective(organizationInfo);
		} catch (Throwable e) {
			try {
				organizationInfo.setCategory("E");
				organizationInfo.setCreateTime(new Date());
				organizationInfo.setUpdateTime(new Date());
				organizationInfoMapper.deleteByPrimaryKey(organizationInfo
						.getOrganizationCode());
				organizationInfoMapper.insertSelective(organizationInfo);
			} catch (Throwable ex) {
				ex.printStackTrace();
			}
		}
	}

	private void saveOrganizationInfo(SynLisLabranchgroup labranchgroup) {
		// 为了保证数据准确性，此处使用销管的内码（即agentgroup），并且通过upbranch来判断上级
		StringBuffer affiliationCode = new StringBuffer();
		StringBuffer affiliationName = new StringBuffer();
		StringBuffer wholeOrganizationCode = new StringBuffer();
		StringBuffer wholeOrganizationName = new StringBuffer();
		OrganizationInfo organizationInfo = new OrganizationInfo();
		try {
			if (labranchgroup.getAgentgroup() == null
					|| "".equals(labranchgroup.getAgentgroup().trim())) {
				return;
			}
			String agentgroup = labranchgroup.getAgentgroup().trim();
			organizationInfo.setOrganizationCode(agentgroup);
			organizationInfo.setOrganizationName(labranchgroup.getName());
			organizationInfo.setOrganizationShortname(labranchgroup.getName());
			String upAgentgroup = labranchgroup.getUpbranch();

			while (upAgentgroup != null && !"".equals(upAgentgroup.trim())) {

				SynLisLabranchgroup uplabranchgroup = synLislabranchgroupMapper
						.selectByPrimaryKey(upAgentgroup.trim());
				affiliationCode.insert(0, uplabranchgroup.getAgentgroup()
						.trim());
				affiliationCode.insert(0, MDConstants.SEPARATOR_DOT);
				affiliationName.insert(0, uplabranchgroup.getName().trim());
				affiliationName.insert(0, MDConstants.SEPARATOR_SLANT);
				upAgentgroup = uplabranchgroup.getUpbranch();

			}

			if (labranchgroup.getManagecom() == null
					|| "".equals(labranchgroup.getManagecom().trim())) {
				throw new BusinessException("所属管理机构编码异常！");
			} else {
				String managecom = labranchgroup.getManagecom().trim();
				if (managecom.length() == 8
						&& managecom.startsWith(MDConstants.TOP_ORGANIZATION)) {
					OrganizationInfo org = organizationInfoMapper
							.selectByPrimaryKey(managecom);
					if (org != null) {
						affiliationCode.insert(0,
								org.getWholeOrganizationCode());
						affiliationName.insert(0,
								org.getWholeOrganizationName());
					} else {
						affiliationCode.insert(0, managecom);
						affiliationCode.insert(0, MDConstants.SEPARATOR_DOT);
						affiliationCode.insert(0, managecom.substring(0, 6));
						affiliationCode.insert(0, MDConstants.SEPARATOR_DOT);
						affiliationCode.insert(0, managecom.substring(0, 4));
						affiliationCode.insert(0, MDConstants.SEPARATOR_DOT);
						affiliationCode.insert(0, MDConstants.TOP_ORGANIZATION);
						affiliationName.insert(0, synLisLdcomMapper
								.selectByPrimaryKey(managecom).getShortname());
						affiliationName.insert(0, MDConstants.SEPARATOR_SLANT);
						affiliationName.insert(0, synLisLdcomMapper
								.selectByPrimaryKey(managecom.substring(0, 6))
								.getShortname());
						affiliationName.insert(0, MDConstants.SEPARATOR_SLANT);
						affiliationName.insert(0, synLisLdcomMapper
								.selectByPrimaryKey(managecom.substring(0, 4))
								.getShortname());
						affiliationName.insert(0, MDConstants.SEPARATOR_SLANT);
						affiliationName.insert(0,
								MDConstants.TOP_ORGANIZATION_NAME);
					}
				} else {
					throw new BusinessException("所属管理机构编码异常！");
				}
			}

			int totalNumber = 0;
			totalNumber += this.countLaagent(agentgroup);

			wholeOrganizationCode.append(affiliationCode)
					.append(MDConstants.SEPARATOR_DOT).append(agentgroup);
			wholeOrganizationName.append(affiliationName)
					.append(MDConstants.SEPARATOR_SLANT)
					.append(labranchgroup.getName());
			organizationInfo.setAffiliationCode(affiliationCode.toString());
			organizationInfo.setAffiliationName(affiliationName.toString());
			organizationInfo.setWholeOrganizationCode(wholeOrganizationCode
					.toString());
			organizationInfo.setWholeOrganizationName(wholeOrganizationName
					.toString());
			organizationInfo.setTotalNumber(totalNumber);
			organizationInfo.setCategory("1");
			organizationInfo.setChannel(labranchgroup.getBranchtype());
			organizationInfo.setCreateTime(new Date());
			organizationInfo.setUpdateTime(new Date());
			organizationInfoMapper.deleteByPrimaryKey(organizationInfo
					.getOrganizationCode());
			organizationInfoMapper.insertSelective(organizationInfo);
		} catch (Throwable e) {
			try {
				e.printStackTrace();
				organizationInfo.setCategory("E");
				organizationInfo.setCreateTime(new Date());
				organizationInfo.setUpdateTime(new Date());
				organizationInfoMapper.deleteByPrimaryKey(organizationInfo
						.getOrganizationCode());
				organizationInfoMapper.insertSelective(organizationInfo);
			} catch (Throwable ex) {
				ex.printStackTrace();
			}
		}
	}

	// 递归获取外勤用户数
	private int countLaagent(String agentgroup) {
		int totalNumber = 0;
		SynLisLaagentExample example1 = new SynLisLaagentExample();
		SynLisLaagentExample.Criteria criteria1 = example1.createCriteria();
		List<String> agentState = new ArrayList<String>();
		agentState.add("01");
		agentState.add("02");
		criteria1.andAgentstateIn(agentState);
		criteria1.andAgentgroupEqualTo(agentgroup);
		totalNumber += synLisLaagentMapper.countByExample(example1);
		SynLisLabranchgroupExample example2 = new SynLisLabranchgroupExample();
		SynLisLabranchgroupExample.Criteria criteria2 = example2
				.createCriteria();
		criteria2.andUpbranchEqualTo(agentgroup);
		List<SynLisLabranchgroup> synLisLabranchgroupList = synLislabranchgroupMapper
				.selectByExample(example2);
		for (SynLisLabranchgroup labranchgroup : synLisLabranchgroupList) {
			if (labranchgroup != null && labranchgroup.getAgentgroup() != null
					&& !"".equals(labranchgroup.getAgentgroup().trim()))
				totalNumber += countLaagent(labranchgroup.getAgentgroup()
						.trim());
		}

		return totalNumber;
	}


	/* (non-Javadoc)
	 * @see com.hualife.md.member.service.IOrganizationIntegrateService#integrateOU()
	 */
	@Override
	public void integrateOU() {
		logger.info("对来自域控系统中的组织架构数据进行加工处理！");
		SynAdOrganizationalunitExample example1 = new SynAdOrganizationalunitExample();
		SynAdOrganizationalunitExample.Criteria criteria1 = example1
				.createCriteria();
		criteria1.andPidEqualTo("");
		SynAdOrganizationalunit topOU = synAdOrganizationalunitMapper
				.selectByExample(example1).get(0);
		String topName = topOU.getName();
		
		SynAdOrganizationalunitExample example = new SynAdOrganizationalunitExample();
		SynAdOrganizationalunitExample.Criteria criteria = example
				.createCriteria();
		criteria.andIssynedtoouEqualTo(MDConstants.NOT_SYNED);

		List<SynAdOrganizationalunit> adOuList = synAdOrganizationalunitMapper
				.selectByExample(example);
		for (SynAdOrganizationalunit adOu : adOuList) {
			try {
				OrganizationalunitInfo orgunitInfo = new OrganizationalunitInfo();
				orgunitInfo.setOuId(adOu.getUsncreated());
				orgunitInfo.setOuName(adOu.getName());
				StringBuffer ou = new StringBuffer();

				String dnstr = adOu.getDn();
				String[] dnlist = dnstr.split(MDConstants.SEPARATOR_COMMA);
				// int level = 0;
				for (String dn : dnlist) {
					if (dn.startsWith(MDConstants.PREFIX_OrganizationUnit)) { // DN中下级机构在前，所以要反向插入
						String value = dn
								.substring(MDConstants.PREFIX_OrganizationUnit
										.length());
						ou.insert(0, value);
						ou.insert(0, MDConstants.SEPARATOR_SLANT);
					}
				}
				if (ou.length() > 0) {
					ou.insert(0, topName);
//					ou.deleteCharAt(0);
					if (ou.lastIndexOf("/") > 0) {
						orgunitInfo.setWholeOuName(ou.toString());
						orgunitInfo.setAffiliationOuName(ou.delete(
								ou.lastIndexOf("/"), ou.length()).toString());
						
						StringBuffer affiOuId = new StringBuffer();
						StringBuffer wholeOuId = new StringBuffer();
						String pid = adOu.getPid();
						while (pid != null && !"".equals(pid.trim())) {

							SynAdOrganizationalunit uporgunit = synAdOrganizationalunitMapper
									.selectByPrimaryKey(pid.trim());
							affiOuId.insert(0, uporgunit.getUsncreated().trim());
							affiOuId.insert(0, MDConstants.SEPARATOR_DOT);
							pid = uporgunit.getPid();

						}
						if (affiOuId.length() > 0)
							affiOuId.deleteCharAt(0);
						wholeOuId.append(affiOuId)
								.append(MDConstants.SEPARATOR_DOT)
								.append(adOu.getUsncreated());
						orgunitInfo.setAffiliationOuId(affiOuId
								.toString());
						orgunitInfo
								.setWholeOuId(wholeOuId.toString());
					} else {
						orgunitInfo.setAffiliationOuId("");
						orgunitInfo.setAffiliationOuName("");
						orgunitInfo
								.setWholeOuId(adOu.getUsncreated());
						orgunitInfo.setWholeOuName(ou.toString());
					}

				} else {
					orgunitInfo.setAffiliationOuId("");
					orgunitInfo.setAffiliationOuName("");
					orgunitInfo.setWholeOuId(adOu.getUsncreated());
					orgunitInfo.setWholeOuName(adOu.getName());
				}

				int num = adOrganizationalunitQueryMapper
						.queryValidUserNumByDN(dnstr);

				orgunitInfo.setTotalNum(num);
				OrganizationalunitInfo oldorgunitInfo = organizationalunitInfoMapper
						.selectByPrimaryKey(orgunitInfo.getOuId());
				if (oldorgunitInfo == null) {
					orgunitInfo.setWeight(Long
							.parseLong(orgunitInfo.getOuId()));
					orgunitInfo.setCreateTime(new Date());
					orgunitInfo.setUpdateTime(new Date());
					organizationalunitInfoMapper.insert(orgunitInfo);
				} else {
					orgunitInfo.setUpdateTime(new Date());
					organizationalunitInfoMapper
							.updateByPrimaryKeySelective(orgunitInfo);
				}
			} catch (Exception e) {
				logger.error("数据异常，原因是：" + e.getMessage());
			}
			
			
		}

		logger.info("对来自域控系统中的组织架构数据加工处理完毕！");
	}

}

/*
 * 修改历史 $Log$
 */